#!/usr/bin/Rscript
##########################################################################################
# Issue Ownership and Agenda Setting in the 2019 Swiss National Elections
##########################################################################################
# Description:
# Script for Figure A1
##########################################################################################
# Content
##########################################################################################
# 1) Dependencies
# 2) Startup
# 3) Load Data
# 4) Transform Data
# 5) Figure A1
##########################################################################################
# 1) Dependencies
##########################################################################################
library(dplyr)
library(tidyverse)
library(data.table)
library(readr)
library(lubridate)
library(ggplot2)
library(ggExtra)
library(ggeffects)
library(ggrepel)
library(ggforce)
library(igraph)
library(graphlayouts)
library(ggraph)
library(scales)
library(purrr)
library(magrittr)
library(cowplot)
library(sysfonts)
##########################################################################################
# 2) Startup
##########################################################################################
rm(list=ls())
# - set dir
args = commandArgs()

scriptName = args[substr(args,1,7) == '--file=']

if (length(scriptName) == 0) {
  scriptName <- rstudioapi::getSourceEditorContext()$path
} else {
  scriptName <- substr(scriptName, 8, nchar(scriptName))
}

pathName = substr(
  scriptName, 
  1, 
  nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2])
)


# - load fonts used in plots
sysfonts::font_add_google("Montserrat", "Montserrat")
sysfonts::font_add_google("Roboto", "Roboto")

# - load ddl theme
suppressMessages(suppressWarnings(source('../ggplot_theme_ddl.R')))
# - pre-setup for figure 1
ddl_theme_2 <- theme(legend.position = "bottom", legend.title = element_blank(), 
                     strip.background = element_blank(), strip.text = element_text(color = "black"),
                     axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 16, color = "black"),  
                     axis.text.y = element_text(hjust=0, size = 16, color = "black"),
                     axis.ticks.y = element_blank(),
                     strip.text.x = element_text(size = 16, color = "black"),
                     axis.title = element_text(size = 16, color = "black"),
                     legend.text = element_text(size = 16, color = "black"),
                     plot.title = element_blank(),
                     plot.margin = unit(c(.5,.5,.5,.5), "cm"),
                     legend.key.size = unit(1.5,"line"),
                     legend.key = element_blank(),
                     axis.line.x = element_line(color="black", size = .5),
                     axis.line.y = element_line(color="black", size = .5),
                     panel.spacing.y = unit(2, "lines"),
                     panel.spacing.x = unit(.8, "lines")) 

# - set directory
setwd(pathName)
parent_path <- getwd()
##########################################################################################
# 3) Load Data
##########################################################################################
panel <- read_csv("../Data/1184_Selects2019_Panel_Data_v1.0.0.csv", col_types = cols(W1_f20210rec3 = col_double()))
##########################################################################################
# 4) Transform Data
##########################################################################################
ownership <- colnames(panel)[str_detect(colnames(panel),"f15330")]
issues <- unique(str_replace(ownership,"W[1-3]_",""))
names(issues) <- c("Europe","Immigation","Social Policy","Environment","Economic Policy")

df <- panel %>% 
  mutate_at(vars(contains("f15330")),
            funs(case_when(.==1~"FDP",
                           .==2~"CVP",
                           .==3~"SP",
                           .==4~"SVP",
                           .==5~"Greens",
                           .==6~"GLP",
                           .==7~"BDP",
                           .==8~"Lega",
                           .==9~"MCG",
                           .==20~"Others",
                           TRUE~NA_character_))) 

df <- df %>% 
  mutate_at(vars(contains("f1085")),
            funs(case_when(.==10~"Intention to vote\nFDP",
                           .==20~"Intention to vote\nCVP",
                           .==30~"Intention to vote\nSP",
                           .==40~"Intention to vote\nSVP",
                           .==50~"Intention to vote\nGreens",
                           .==60~"Intention to vote\nGLP",
                           .==70~"Intention to vote\nBDP",
                           .==80~"Intention to vote\nLega",
                           .==90~"Intention to vote\nMCG",
                           .==350~"Intention to vote\nOthers",
                           TRUE~"Intention to vote\nOthers"))) 
##########################################################################################
# 5) Figure 1
##########################################################################################
variables_panel <- c("W1_f15330a", "W1_f15330d", "W1_f15330b")
topics_panel <- c("Europe", "Environment", "Immigration")

for(i in 1:length(variables_panel)) {
  tmp <- df %>% dplyr::select(c("id", "W1_f1085_90", variables_panel[i]))
  tmp$vars <- variables_panel[i]
  colnames(tmp) <- c("id", "vote_intention", "vals_2", "vars")
  
  tmp <- tmp %>% dplyr::filter(!is.na(vote_intention) == T) %>% 
                 dplyr::filter(is.na(vals_2) == F) %>%
                 dplyr::filter(is.na(vars) == F) %>%
                 dplyr::group_by(vote_intention, vals_2) %>%
                 summarise(n = n()) %>% 
                 dplyr::mutate(topic = topics_panel[i])
  if(i == 1){
    pl <- tmp
  } else {
    pl <- dplyr::bind_rows(pl,tmp)
  }
  rm(tmp)
}

pl <- pl %>%  dplyr::group_by(topic, vote_intention) %>% 
              dplyr::mutate(n.cand = sum(n)) %>%
              dplyr::mutate(frac = n / n.cand) %>% 
              dplyr::filter(vals_2 %in% c("FDP", "CVP", "SP", "SVP", "Greens", "GLP")) %>% 
              dplyr::filter(vote_intention %in% c("Intention to vote\nFDP", "Intention to vote\nCVP", 
                                                  "Intention to vote\nSP", "Intention to vote\nSVP", 
                                                  "Intention to vote\nGreens", "Intention to vote\nGLP")) %>%
              dplyr::ungroup() %>% 
              tidyr::complete(vote_intention, nesting(vals_2, topic)) %>% 
              dplyr::mutate(frac = ifelse(is.na(frac) == T, 0, frac)) %>%
              dplyr::arrange(vote_intention, topic, frac) %>% 
              dplyr::mutate(order = row_number()) %>% 
              dplyr::mutate(topic = fct_relevel(topic, "Environment", "Europe", "Immigration")) 

topics_filter <- c("Environment","Europe", "Immigration")
values <- c("#009E73","#0072B2","#999999")
plots <- list()

for(k in 1:length(topics_filter)){
  pl_filter <- pl %>% dplyr::filter(topic == topics_filter[k])
  
  plots[[k]] <-  ggplot(data = pl_filter, aes(y = frac, x = order, fill = topic)) +
    geom_col(position = position_dodge(width = 0.8), width=0.75) +
    facet_wrap(~ vote_intention, scales = "free_y", ncol = 1, nrow = 6) +
    scale_x_continuous(breaks = pl_filter$order,
                       labels = pl_filter$vals_2,
                       expand = c(0,0)) +
    scale_y_continuous(labels = scales::percent) +
    scale_color_manual(labels = topics_filter[k], 
                       values = values[k]) +
    scale_fill_manual(labels = topics_filter[k], 
                      values = values[k]) +
    labs(x = "Party", y = "Share of respondents", 
         title = "Which is the most competent Party in the following Topics:") +
    coord_flip() +
    ddl_theme_2 +
    theme(legend.position = "none", legend.title = element_text(size = 16, color = "black"), 
          strip.background = element_blank(), strip.text = element_text(color = "black"),
          axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12, color = "black"),  
          axis.text.y = element_text(hjust=.5, size = 12, color = "black"),
          strip.text.x = element_text(size = 12, color = "black"),
          axis.title = element_text(size = 14, color = "black"),
          plot.title = element_blank(),
          legend.text = element_text(size = 14, color = "black"),
          legend.key = element_blank(),
          plot.margin = unit(c(.5,.5,.5,.5), "cm"),
          legend.key.size = unit(1.5,"line"),
          axis.line.x = element_line(color="black", size = .5),
          axis.line.y = element_line(color="black", size = .5),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.border = element_blank(),
          panel.background = element_blank())
  
}

pl2_i <- cowplot::plot_grid(plotlist = plots, align = "hv", ncol = 3, label_x = c(0.15,0.37,0.2),
                            labels = topics_filter, label_size = 16, label_fontface = "bold")

pl2_i

ggsave(filename = paste0("../images/figure_A1.pdf"), width = 21, height = 28, device = cairo_pdf, units = "cm")
